package org.zhangkun.jmsg.ui.swing;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JComboBox;

import org.zhangkun.jmsg.core.UserManager;
import org.zhangkun.jmsg.core.network.NetConnection;
import org.zhangkun.jmsg.util.ConfigManager;
import org.zhangkun.jmsg.util.GlobalVar;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JCheckBox;
import javax.swing.JRadioButton;
import javax.swing.BoxLayout;
import javax.swing.border.TitledBorder;
import javax.swing.ButtonGroup;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.util.ArrayList;

import javax.swing.JTable;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.border.EtchedBorder;

public class SetDialog extends JDialog {

	private class NetAddresTableModel implements TableModel {
		private String newIpPrefix;
		private String newStartIp;
		private String newEndIp;

		@Override
		public int getRowCount() {
			// TODO Auto-generated method stub
			return GlobalVar.SCAN_IP.size() + 1;
		}

		@Override
		public int getColumnCount() {
			// TODO Auto-generated method stub
			return 2;
		}

		@Override
		public String getColumnName(int columnIndex) {
			// TODO Auto-generated method stub
			if (columnIndex == 1)
				return "开始IP";
			if (columnIndex == 2)
				return "结束IP";
			return null;
		}

		@Override
		public Class<?> getColumnClass(int columnIndex) {
			// TODO Auto-generated method stub
			return String.class;
		}

		@Override
		public boolean isCellEditable(int rowIndex, int columnIndex) {
			// TODO Auto-generated method stub
			if (rowIndex >= GlobalVar.SCAN_IP.size()) {
				if (columnIndex == 1)
					if (newStartIp == null || newStartIp.equals(""))
						return false;
				return true;
			}
			String ips = GlobalVar.SCAN_IP.get(rowIndex);
			ArrayList<String> useAddres = NetConnection.instance
					.getUsableAddres();
			for (int i = 0; i < useAddres.size(); i++)
				if (ips.equals(NetConnection.instance.getScanIp(useAddres
						.get(i))))
					return false;
			return true;
		}

		@Override
		public Object getValueAt(int rowIndex, int columnIndex) {
			// TODO Auto-generated method stub
			if (rowIndex >= GlobalVar.SCAN_IP.size())
				if (columnIndex == 0)
					return newIpPrefix == null ? ""
							: newIpPrefix + newStartIp == null ? ""
									: newStartIp;
				else if (columnIndex == 1)
					return newIpPrefix == null ? ""
							: newIpPrefix + newEndIp == null ? "" : newEndIp;
			String ips = GlobalVar.SCAN_IP.get(rowIndex);
			String[] ip = ips.split(",");
			return ip[0] + ip[columnIndex + 1];
		}

		@Override
		public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
			// TODO Auto-generated method stub
			String ip = (String) aValue;
			if (columnIndex == 0 && ip == null || ip.equals(""))
				return;
			if (columnIndex == 0) {
				if (ip.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) {
					newIpPrefix = ip.substring(0, ip.lastIndexOf(".")) + ".";
					if (rowIndex >= GlobalVar.SCAN_IP.size()) {
						newStartIp = ip.substring(ip.lastIndexOf(".") + 1);
						if (newEndIp == null || newEndIp.equals(""))
							setValueAt(aValue, rowIndex, 1);
						else {
							GlobalVar.SCAN_IP.add(newIpPrefix + ","
									+ newStartIp + "," + newEndIp);
						}
					} else {
						String oldip = GlobalVar.SCAN_IP.get(rowIndex);
						String[] oldips = oldip.split(",");
						oldips[0] = ip.substring(0, ip.lastIndexOf(".")) + ".";
						oldips[1] = ip.substring(ip.lastIndexOf(".") + 1);
						GlobalVar.SCAN_IP.set(rowIndex, oldips[0] + ","
								+ oldips[1] + "," + oldips[2]);
					}
				} else {
					JOptionPane.showMessageDialog(SetDialog.this,
							"IP地址格式错误，请输入IPv4格式的IP地址。");
				}
			} else if (columnIndex == 1) {
				if (ip.matches("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}")) {
					if (ip.startsWith(newIpPrefix)) {
						if (rowIndex >= GlobalVar.SCAN_IP.size()) {
							newIpPrefix = ip.substring(0, ip.lastIndexOf("."))
									+ ".";
							newEndIp = ip.substring(ip.lastIndexOf(".") + 1);
							if (newStartIp == null || newStartIp.equals(""))
								GlobalVar.SCAN_IP.add(newIpPrefix + ","
										+ newStartIp + "," + newEndIp);
							else {
								setValueAt(aValue, rowIndex, 0);
							}
							newStartIp = "";
							newEndIp = "";
						} else {
							String oldip = GlobalVar.SCAN_IP.get(rowIndex);
							String[] oldips = oldip.split(",");
							oldips[0] = ip.substring(0, ip.lastIndexOf("."))
									+ ".";
							oldips[2] = ip.substring(ip.lastIndexOf(".") + 1);
							GlobalVar.SCAN_IP.set(rowIndex, oldips[0] + ","
									+ oldips[1] + "," + oldips[2]);
						}
					} else {
						JOptionPane.showMessageDialog(SetDialog.this,
								"开始地址和结束地址必须在同一网段。");
					}
				} else {
					JOptionPane.showMessageDialog(SetDialog.this,
							"IP地址格式错误，请输入IPv4格式的IP地址。");
				}
			}
		}

		@Override
		public void addTableModelListener(TableModelListener l) {
			// TODO Auto-generated method stub

		}

		@Override
		public void removeTableModelListener(TableModelListener l) {
			// TODO Auto-generated method stub

		}
	}

	public static SetDialog instance;
	/**
	 * 
	 */
	private static final long serialVersionUID = 7088104415676726411L;

	public synchronized static void create(MainWindow frm) {
		if (instance == null) {
			instance = new SetDialog(frm);
			instance.init();
		} else {
			instance.setVisible(true);
			instance.setFocusable(true);
		}
	}

	private final ButtonGroup buttonGroup = new ButtonGroup();
	private final ButtonGroup buttonGroup_1 = new ButtonGroup();
	private JCheckBox checkBox;
	private JPanel panel_89 = new JPanel();
	private MainWindow frm;

	private JTextField textField;
	private JComboBox groupBox;
	private JComboBox charsetBox;
	private JTable table;
	private JPanel contentPanel;

	/**
	 * Create the dialog.
	 * 
	 * @param actionListener
	 */
	public SetDialog(MainWindow f) {
		super(f);
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				SetDialog.instance.setVisible(false);
				SetDialog.instance.dispose();
				SetDialog.instance = null;
			}
		});
		this.frm = f;
		// init();
	}

	private void init() {
		this.setTitle("设置");
		setBounds(100, 100, 447, 300);
		this.setModal(true);
		this.setLocationRelativeTo(frm);
		getContentPane().setLayout(new BorderLayout());
		UserManager.instance.getGroups();

		JPanel titlePanel = new JPanel();
		getContentPane().add(titlePanel, BorderLayout.NORTH);
		titlePanel.setLayout(new BorderLayout(0, 0));

		JLabel label_3 = new JLabel("设置：");
		titlePanel.add(label_3, BorderLayout.WEST);

		JComboBox comboBox_2 = new JComboBox(new String[] { "基本设置", "网络设置" });
		comboBox_2.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if (e.getItem().equals("基本设置")) {
					((CardLayout) contentPanel.getLayout()).show(contentPanel,
							"CommonSet");
				} else if (e.getItem().equals("网络设置")) {
					((CardLayout) contentPanel.getLayout()).show(contentPanel,
							"NetSet");
				}
			}
		});
		comboBox_2.setMaximumRowCount(10);
		titlePanel.add(comboBox_2);

		contentPanel = new JPanel();
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(new CardLayout(0, 0));

		JPanel panel_6 = new JPanel();
		JPanel panel_12 = new JPanel();
		contentPanel.add(panel_12, "NetSet");
		panel_12.setLayout(new GridLayout(0, 1, 0, 0));

		JPanel panel_13 = new JPanel();
		panel_12.add(panel_13);
		panel_13.setLayout(new BorderLayout(5, 5));

		JLabel label_5 = new JLabel("扫描网络地址：");
		panel_13.add(label_5, BorderLayout.NORTH);

		table = new JTable();
		table.setModel(new DefaultTableModel(new Object[][] {}, new String[] {
				"\u8D77\u59CB\u5730\u5740", "New column" }));
		table.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		table.setModel(new NetAddresTableModel());
		panel_13.add(table);

		JPanel panel_7 = new JPanel();
		panel_13.add(panel_7, BorderLayout.SOUTH);
		panel_7.setLayout(new BorderLayout(0, 0));

		JLabel label_6 = new JLabel("刷新线程数：");
		panel_7.add(label_6, BorderLayout.WEST);

		JComboBox comboBox = new JComboBox(new String[] { "1", "2", "3", "4",
				"5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15",
				"16", "17", "18", "19", "20", "21", "22", "23", "24", "25",
				"26", "27", "28", "29", "30", "31", "32", "33", "34", "35",
				"36", "37", "38", "39", "40", "41", "42", "43", "44", "45",
				"46", "47", "48", "49", "50" });
		comboBox.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				GlobalVar.SCAN_THREADS = Integer.parseInt((String) e.getItem());
			}
		});
		comboBox.setSelectedItem(GlobalVar.SCAN_THREADS + "");
		panel_7.add(comboBox);
		contentPanel.add(panel_6, "CommonSet");

		panel_6.setLayout(new BorderLayout(0, 0));
		panel_6.add(panel_89, BorderLayout.CENTER);
		panel_89.setBorder(new TitledBorder(null, "\u57FA\u672C\u8BBE\u7F6E",
				TitledBorder.LEADING, TitledBorder.TOP, null, null));
		GridBagLayout gbl_panel_89 = new GridBagLayout();
		gbl_panel_89.columnWidths = new int[] { 419, 0 };
		gbl_panel_89.rowHeights = new int[] { 36, 44, 55, 0 };
		gbl_panel_89.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
		gbl_panel_89.rowWeights = new double[] { 0.0, 0.0, 0.0,
				Double.MIN_VALUE };
		panel_89.setLayout(gbl_panel_89);

		JPanel panel_5 = new JPanel();
		panel_5.setAlignmentY(Component.TOP_ALIGNMENT);
		GridBagConstraints gbc_panel_5 = new GridBagConstraints();
		gbc_panel_5.fill = GridBagConstraints.HORIZONTAL;
		gbc_panel_5.gridx = 0;
		gbc_panel_5.gridy = 0;
		panel_89.add(panel_5, gbc_panel_5);

		JPanel panel_9 = new JPanel();
		panel_9.setLayout(new BorderLayout(0, 0));

		JLabel label = new JLabel("昵称：");
		panel_9.add(label, BorderLayout.WEST);

		textField = new JTextField(UserManager.me.getName());
		panel_9.add(textField);

		JPanel panel_10 = new JPanel();
		panel_10.setLayout(new BorderLayout(0, 0));

		JLabel label_1 = new JLabel("组名：");
		panel_10.add(label_1, BorderLayout.WEST);
		groupBox = new JComboBox(UserManager.instance.getGroups());
		panel_10.add(groupBox);
		groupBox.setEditable(true);
		groupBox.setSelectedItem(UserManager.me.getGroup());
		panel_5.setLayout(new BoxLayout(panel_5, BoxLayout.X_AXIS));
		panel_5.add(panel_9);
		panel_5.add(panel_10);

		JPanel panel_4 = new JPanel();
		GridBagConstraints gbc_panel_4 = new GridBagConstraints();
		gbc_panel_4.fill = GridBagConstraints.HORIZONTAL;
		gbc_panel_4.gridx = 0;
		gbc_panel_4.gridy = 1;
		panel_89.add(panel_4, gbc_panel_4);
		panel_4.setLayout(new BoxLayout(panel_4, BoxLayout.LINE_AXIS));

		JLabel label_2 = new JLabel("消息编码：");
		panel_4.add(label_2);

		charsetBox = new JComboBox(new String[] { "gb2312", "utf-8", "gbk" });
		charsetBox.setEditable(true);
		charsetBox.setSelectedItem(GlobalVar.TRANSPORT_ENCODING);
		charsetBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				String c = ((String) charsetBox.getSelectedItem()).trim();
				try {
					"".getBytes(c);
					GlobalVar.TRANSPORT_ENCODING = c;
				} catch (Exception e1) {
					JOptionPane.showMessageDialog(SetDialog.this, "不支持该编码！");
					charsetBox.setSelectedIndex(0);
				}
			}
		});

		panel_4.add(charsetBox);

		JLabel label_4 = new JLabel("此设置可能会造成中文乱码。");
		label_4.setForeground(Color.RED);
		panel_4.add(label_4);

		JPanel panel_11 = new JPanel();
		GridBagConstraints gbc_panel_11 = new GridBagConstraints();
		gbc_panel_11.fill = GridBagConstraints.HORIZONTAL;
		gbc_panel_11.gridx = 0;
		gbc_panel_11.gridy = 2;
		panel_89.add(panel_11, gbc_panel_11);
		panel_11.setLayout(new BoxLayout(panel_11, BoxLayout.X_AXIS));

		JPanel panel_3 = new JPanel();
		panel_11.add(panel_3);
		panel_3.setLayout(new BoxLayout(panel_3, BoxLayout.X_AXIS));

		JPanel panel = new JPanel();
		panel_3.add(panel);
		panel.setBorder(new TitledBorder(null, "\u6C14\u6CE1\u63D0\u793A",
				TitledBorder.LEADING, TitledBorder.TOP, null, null));
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

		checkBox = new JCheckBox("上下线消息提示");
		panel.add(checkBox);
		checkBox.setSelected(GlobalVar.TRAY_MSG);

		final JCheckBox checkBox_1 = new JCheckBox("文件传送消息提示");
		panel.add(checkBox_1);
		checkBox_1.setSelected(GlobalVar.TRAY_FILE_MSG);

		JPanel panel_1 = new JPanel();
		panel_3.add(panel_1);
		panel_1.setBorder(new TitledBorder("\u6587\u4EF6\u63D0\u793A"));
		panel_1.setLayout(new BoxLayout(panel_1, BoxLayout.Y_AXIS));

		final JRadioButton radioButton = new JRadioButton("直接弹出");
		radioButton.setSelected(GlobalVar.FILE_DIRECT_POP_UP);
		radioButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				GlobalVar.FILE_DIRECT_POP_UP = true;
			}
		});
		buttonGroup.add(radioButton);
		panel_1.add(radioButton);

		final JRadioButton radioButton_1 = new JRadioButton("头像闪烁");
		radioButton_1.setSelected(!GlobalVar.FILE_DIRECT_POP_UP);
		radioButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				GlobalVar.FILE_DIRECT_POP_UP = false;
			}
		});
		buttonGroup.add(radioButton_1);
		panel_1.add(radioButton_1);

		JPanel panel_2 = new JPanel();
		panel_3.add(panel_2);
		panel_2.setBorder(new TitledBorder("\u6D88\u606F\u63D0\u793A"));
		panel_2.setLayout(new BoxLayout(panel_2, BoxLayout.Y_AXIS));

		final JRadioButton radioButton_2 = new JRadioButton("直接弹出");
		radioButton_2.setSelected(GlobalVar.MSG_DIRECT_POP_UP);
		radioButton_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				GlobalVar.MSG_DIRECT_POP_UP = true;
			}
		});
		buttonGroup_1.add(radioButton_2);
		panel_2.add(radioButton_2);

		final JRadioButton radioButton_3 = new JRadioButton("头像闪烁");
		radioButton_3.setSelected(!GlobalVar.MSG_DIRECT_POP_UP);
		radioButton_3.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				GlobalVar.MSG_DIRECT_POP_UP = false;
			}
		});

		buttonGroup_1.add(radioButton_3);
		panel_2.add(radioButton_3);
		checkBox_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				GlobalVar.TRAY_FILE_MSG = true;
			}
		});
		checkBox_1.setSelected(GlobalVar.TRAY_MSG);
		checkBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				GlobalVar.TRAY_MSG = false;
			}
		});
		// checkBox.setSelected(!GlobalVar.TRAY_MSG);
		{
			JPanel buttonPanel = new JPanel();
			getContentPane().add(buttonPanel, BorderLayout.SOUTH);
			buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
			{
				JButton okButton = new JButton("确认");
				okButton.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						GlobalVar.GROUP = (String) groupBox.getSelectedItem();
						GlobalVar.NAME = textField.getText();
						UserManager.me.setName(GlobalVar.NAME);
						UserManager.me.setGroup(GlobalVar.GROUP);
						SetDialog.instance.setVisible(false);
						SetDialog.instance.dispose();
						SetDialog.instance = null;
						ConfigManager.saveConfig();
						frm.refresh();
					}
				});
				{
					JButton cancelButton = new JButton("取消");
					cancelButton.addActionListener(new ActionListener() {

						@Override
						public void actionPerformed(ActionEvent e) {
							// TODO Auto-generated method stub
							SetDialog.instance.setVisible(false);
							SetDialog.instance.dispose();
							SetDialog.instance = null;
						}
					});
					cancelButton.setActionCommand("取消");
					buttonPanel.add(cancelButton);
				}
				buttonPanel.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
		}
		this.setVisible(true);
	}

	public JComboBox getCharsetBox() {
		return charsetBox;
	}

	public JPanel getContentPanel() {
		return contentPanel;
	}
}
